package pbbltobpel;

import java.util.HashSet;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import pbbltobpel.parser.PddlPlan;

import com.predic8.wsdl.Definitions;
import com.predic8.wsdl.Service;

public class Deployer {
	public static Document getDeployFile(PddlPlan plan) throws ParserConfigurationException
	{
		DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        
        String name = plan.getFileName();
        Element root = doc.createElement("deploy");
        root.setAttribute("xmlns:" + name, name);
        root.setAttribute("xmlns", "http://www.apache.org/ode/schemas/dd/2007/03");
        doc.appendChild(root);
        
        Element process = doc.createElement("process");
        process.setAttribute("name", name + ":" + name);
        root.appendChild(process);
        
        Element active = doc.createElement("active");
        active.setTextContent("true");
        process.appendChild(active);
        
        Element retired = doc.createElement("retired");
        retired.setTextContent("false");
        process.appendChild(retired);
        
        Element processeventsgenerate = doc.createElement("process-events");
        processeventsgenerate.setAttribute("generate", "all");
        process.appendChild(processeventsgenerate);
        
        Element provide = doc.createElement("provide");
        provide.setAttribute("partnerLink", "client");
        process.appendChild(provide);
        
        Element provideService = doc.createElement("service");
        provideService.setAttribute("name", name + ":" + name);
        provideService.setAttribute("port", name + "Port");
        provide.appendChild(provideService);
              
        HashSet<String> set = new HashSet<String>();
        for(String key : plan.getWsdls().keySet())
        {
        	Definitions def = plan.getWsdls().get(key);
        	for(Service s : def.getServices())
        	{
            	String namespace = def.getTargetNamespace();
            	String nskey = s.getName();
            	
            	if(!set.contains(namespace))
            	{
            		set.add(namespace);
            		root.setAttribute("xmlns:" + key, namespace);
            	}
            	
            	Element invoke = doc.createElement("invoke");
            	invoke.setAttribute("partnerLink", nskey);
            	process.appendChild(invoke);
            	
            	Element service = doc.createElement("service");
            	service.setAttribute("name", key + ":" + nskey);
            	service.setAttribute("port", s.getPorts().get(0).getName());
            	invoke.appendChild(service);

        	}
        }
        
        return doc;
	}
	
	
}
